class BinaryIndexedTree:
    def __init__(self, n):
        self.n = n
        self.c = [0] * (n + 1)

    @staticmethod
    def lowbit(x):
        return x & -x

    def update(self, x, delta):
        while x <= self.n:
            self.c[x] += delta
            x += BinaryIndexedTree.lowbit(x)

    def query(self, x):
        s = 0
        while x > 0:
            s += self.c[x]
            x -= BinaryIndexedTree.lowbit(x)
        return s


class Solution:
    def createSortedArray(self, instructions: List[int]) -> int:
        n = max(instructions)
        tree = BinaryIndexedTree(n)
        ans = 0
        for num in instructions:
            a = tree.query(num - 1)
            b = tree.query(n) - tree.query(num)
            ans += min(a, b)
            tree.update(num, 1)
        return ans % int((1e9 + 7))
